package org.wingstudio.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
/*import org.wingstudio.util.jacob.Office2PDF;*/

/**
 * 文档转换
 * 
 * @author 唐家林
 * @time 2014年10月21日
 */
public class DocumentConverterUtil {
	private static Logger logger = LoggerFactory.getLogger(DocumentConverterUtil.class);

	/**
	 * 连接OpenOfiice的默认端口
	 */
	private static final int DEFAULT_PORT = 8100;

	/**
	 * 文档转换的文档
	 */
	private File FILE;

	/**
	 * 生成的PDF文件路径
	 */
	private File PDF_FILE;

	public static File conver (
			String filePath,
			String pdfFolderPath,
			boolean constraint,
			boolean deletePdf ) throws Exception {
		DocumentConverterUtil dc = new DocumentConverterUtil();

		if (isEmptyPath(filePath)) {
			throw new RuntimeException("路径不能为空");
		}
		// 一些初始化工作
		dc.init(filePath, pdfFolderPath);
		dc.converterToPDF(constraint);

		return dc.PDF_FILE;
	}


	/**
	 * 判断路是否为空
	 * 
	 * @param path
	 *
	 * @return 为空返回true,不为空返回false
	 */
	public static boolean isEmptyPath(String path) {
		return null == path || path.isEmpty();
	}
	
	/**
	 * 是否为PDF文件
	 * 
	 * @param fileName
	 *            文件名称(可以是文件名(必须带格式),可以是文件完整路径)
	 * @return 是PDF文件返回true,否则返回false
	 */
	public static boolean isPDF(String fileName) {
		if (isEmptyPath(fileName)) {return false;}
		String regex = ".*\\.pdf";
		return fileName.toLowerCase().matches(regex);
	}
	
	/**
	 * 读取输出的文件,以此等待文件输出完成,否则文件在还converterPDFToSWF未生成则返回了导致打开文件失败
	 * @param in 输入流
	 * @return 返回读取的信息
	 * @throws IOException
	 */
	private static void loadStream(InputStream in) throws IOException {
		in = new BufferedInputStream(in);
		while (in.read() != -1);
		in.close();
	}

	public String converterToPDF(boolean constraint) throws Exception {
		if (!FILE.exists()) {
			log("PDF转换异常，需要转换的文档不存在，无法转换");
			throw new RuntimeException("PDF转换异常，需要转换的文档不存在，无法转换");
		}
		if (!PDF_FILE.exists() || constraint) {
			// 判断父文件夹是否存在,如果不存在则递归生成所需文件夹
			if (!PDF_FILE.getParentFile().exists()) {
				PDF_FILE.getParentFile().mkdirs();
			}
			ExecutorService executor = Executors.newSingleThreadExecutor();
			//这里我修改了端口号
			final OpenOfficeConnection connection = new SocketOpenOfficeConnection(DEFAULT_PORT);
			FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>(){
				public Boolean call() throws Exception {
					try {
						connection.connect();
						DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
						converter.convert(FILE, PDF_FILE);
						return true;
					} catch (java.net.ConnectException e) {
						String msg1 = "PDF转换器异常，OpenOffice服务未启动！";
						log(msg1);
						throw new RuntimeException(msg1 + "\r\n", e);
					} catch (OpenOfficeException e) {
						log("PDF转换器异常，读取转换文件失败");
						throw new RuntimeException("PDF转换器异常，读取转换文件失败", e);
					}
				}
			});
			try {
				executor.execute(future);
				boolean isSuccess = future.get(60, TimeUnit.SECONDS);
				if (!isSuccess) { throw new RuntimeException("文件转换失败,转换超时"); }
			} catch (RuntimeException e) {
				throw e;
			} catch (InterruptedException | ExecutionException e) {
				throw new RuntimeException("文件转换失败", e);
			} catch (TimeoutException e) {
				throw new RuntimeException("文件转换失败,转换超时", e);
			} finally {
				if (null != connection) { connection.disconnect(); }
				if (null != executor && !executor.isShutdown()) { executor.shutdown(); }
			}
			log("PDF转换成功，PDF输出：" + PDF_FILE.getPath());
		} else {
			log("已经转换为PDF，不需要再进行转换");
		}
		log(PDF_FILE.getPath());
		return null;
	}

	private void init(
			String filePath,
			String pdfFolderPath) {
		System.out.println("test filePathhehehehhehehehehhe："+filePath);
		FILE = new File(filePath);
		if(FILE.exists()){
			System.out.println("存在！");
		}
		// 去掉后缀名,取得输出文件的路径和名称
		String outPath = filePath.substring(0, filePath.lastIndexOf("."));
		String fileName = FILE.getName();
		System.out.println("test fileName:"+fileName);
		fileName = File.separator + fileName.substring(0, fileName.lastIndexOf("."));
		
		if (isPDF(filePath)) {
			PDF_FILE = new File(filePath);
		} else {
			PDF_FILE = new File((isEmptyPath(pdfFolderPath) ? outPath : (pdfFolderPath + fileName)) + ".pdf");
		}
		//SWF_FILE = new File((isEmptyPath(swfFolderPath) ? outPath : (swfFolderPath + fileName)) + ".swf");
	}

	/**
	 * 调试日志输出
	 * 
	 * @param msg
	 */
	private static void log(String msg) {
		if (logger.isDebugEnabled()) {
			logger.debug(msg);
		}
	}
}